package com.secsbrain.cloudconsole.web.controller;

import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.secsbrain.cloudconsole.biz.constant.EnumDefinition;
import com.secsbrain.cloudconsole.dal.model.WorkComment;
import com.secsbrain.cloudconsole.dal.model.WorkSheet;
import com.secsbrain.cloudconsole.remote.SsoRemoteService;
import com.secsbrain.common.ResponseResult;
import com.secsbrain.frame.lock.Callback;
import com.secsbrain.frame.lock.DistributedLockTemplate;
import com.secsbrain.sso.core.SsoHelper;
import com.secsbrain.sso.model.dto.system.UserDetailDTO;
import com.secsbrain.sso.service.provider.HttpRequestValueProvider;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.plugins.Page;
import com.secsbrain.cloudconsole.biz.IWorkCommentService;
import com.secsbrain.cloudconsole.biz.IWorkSheetService;
import com.secsbrain.cloudconsole.biz.constant.RoleCodeConstants;
import com.secsbrain.cloudconsole.biz.utils.WorkSheetUtils;
import com.secsbrain.common.ErrorCodeEnum;
import com.secsbrain.common.ResponseVo;
import com.secsbrain.common.concurrent.ExecutorManager;

@RestController
@RequestMapping("/comment")
public class CommentController {
    
    private static final Logger logger = LoggerFactory.getLogger(CommentController.class);
    
    @Autowired
    private DistributedLockTemplate distributedLockTemplate;
    
    @Autowired
    private IWorkCommentService commentService;
    
    @Autowired
	private IWorkSheetService workSheetService;
    
	@Autowired
	private SsoRemoteService userServiceFacade;
	
	@Resource(name="appcode")
	HttpRequestValueProvider<String> appCodeValueProvider;
    
    /**
     * @apiVersion 1.0.0
     * @api {GET} /comment/list 沟通记录列表
     * @apiGroup Comment
     * 
     * @apiParam {Number} workSheetId 	工单ID
     * 
     * @apiSuccess {Object[]} data         数据列表
     * @apiSuccess {Number} data.id 	        评论ID
     * @apiSuccess {Number} data.userId    沟通人ID
     * @apiSuccess {Number} data.roleCode  沟通人角色code
     * @apiSuccess {String} data.userName  沟通人姓名
     * @apiSuccess {String} data.imageUrl  沟通人头像
     * @apiSuccess {String} data.content   消息内容
     * @apiSuccess {Date} data.createTime  沟通时间
     * 
     */
    @RequestMapping(value="/list",method=RequestMethod.GET)
    @ResponseBody
    public ResponseResult<Page<WorkComment>> list(HttpServletRequest httpServletRequest,
                                              @RequestParam(value = "page", defaultValue = "1")Integer page,
                                              @RequestParam(value = "limit", defaultValue = "100")Integer limit, Long workSheetId){
		Assert.notNull(workSheetId,"工单ID不能为空");
    	
    	WorkComment workCommentParam=new WorkComment();
    	workCommentParam.setSourceId(workSheetId);
    	workCommentParam.setSourceType(1);
    	workCommentParam.setIstatus(0);

		Page<WorkComment> pageBean=new Page<WorkComment>(page, limit);
		Page<WorkComment> workCommentPageList=commentService.selectPage(pageBean, workCommentParam);
		
		if(CollectionUtils.isEmpty(workCommentPageList.getRecords())){
	    	return new ResponseResult(workCommentPageList);
		}
		
		Set<Long> userIdSet=new HashSet<Long>();
		for(WorkComment workComment:workCommentPageList.getRecords()){
			userIdSet.add(workComment.getUserId());
		}
		ResponseResult<List<UserDetailDTO>> userVo=userServiceFacade.getRoleDTOsByUserId(appCodeValueProvider.getValue(httpServletRequest), userIdSet.toArray(new Long[userIdSet.size()]));
		Map<Long, UserDetailDTO> userMap=new HashMap<>();
		for(UserDetailDTO userDetailDTO:userVo.getData()){
			userMap.put(userDetailDTO.getId(), userDetailDTO);
		}
		
		for(WorkComment workComment:workCommentPageList.getRecords()){
			UserDetailDTO userDetailDTO=userMap.get(workComment.getUserId());
			workComment.setRoleCode(userDetailDTO.getUserRoleList().get(0).getCode());
			workComment.setUserName(userDetailDTO.getNickname());
			workComment.setImageUrl(userDetailDTO.getAvatar());
		}
    	return new ResponseResult(workCommentPageList);
    }
    
    /**
     * @apiVersion 1.0.0
     * @api {POST} /comment/insert 提交留言
     * @apiGroup Comment
     * 
     * @apiParam {String} content   沟通内容
     * @apiParam {Number} sourceId  工单ID
     * 
     */
    @RequestMapping(value="/insert",method=RequestMethod.POST)
    @ResponseBody
    public ResponseResult<?> insert(HttpServletRequest httpServletRequest,@RequestBody WorkComment comment){
        Assert.hasText(comment.getContent(), "沟通内容不能为空");
        Assert.hasText(comment.getContent().trim(), "沟通内容不能为空");
        Assert.notNull(comment.getSourceId(), "工单ID不能为空");
        
        WorkSheet workSheet=workSheetService.selectById(comment.getSourceId());
		Assert.notNull(workSheet, "没有找到相应的工单");
		Assert.isTrue(!EnumDefinition.WorkSheetStatus.CLOSE.equals(workSheet.getIstatus()), "工单已关闭");
        
		UserDetailDTO userDetailDTO= SsoHelper.currentUser();
		Assert.isTrue(userDetailDTO.getId().equals(workSheet.getCreatorId())
				||WorkSheetUtils.hasIncludeRole(userDetailDTO.getUserRoleList(), RoleCodeConstants.OPS), "权限不足");

		ResponseVo<?> responseVo = (ResponseVo<?>) distributedLockTemplate.execute("insert_comment_"+userDetailDTO.getId(), 0, new Callback() {
            
            @Override
            public Object onGetLock() throws InterruptedException {
                logger.debug("新增留言：{}",comment);
                
                try {
                   commentService.addComment(comment.getContent(), comment.getSourceId());
				} catch (Exception e) {
					logger.error("",e);
					return ErrorCodeEnum.ERROR_COMMON_SYSTEM.getResponseVo(e.getMessage());
				}
				return ResponseVo.getSuccessResponse();
            }
            
            @Override
            public Object onTimeout() throws InterruptedException {
				return ErrorCodeEnum.ERROR_COMMON_SYSTEM.getResponseVo("重复提交");
            }
            
        });
        
		if(responseVo.isSuccess()){
			try {
				String appCode=appCodeValueProvider.getValue(httpServletRequest);
	   			ExecutorManager.getInstance().execute(new Runnable() {
	   				
	   				@Override
	   				public void run() {
	   					commentService.sendWorkSheetDynamic(workSheet,userDetailDTO,-1,comment.getContent(),appCode);
	   				}
	   			});
	   		} catch (Exception e1) {
	   			logger.error("",e1);
	   		}
		}
        return new ResponseResult();
    }
    
}
